using UnityEngine;
using System.Collections;

public class Instantiate : MonoBehaviour {

    public Transform player;
	
	public GameObject[] respawns;
	public GameObject[] players;
    
	void OnNetworkLoadedLevel(int id)
    {
		if(respawns != null)
		{
			if (respawns.Length < id)
				id = id - respawns.Length;
			
	        Network.Instantiate(player, respawns[id].transform.position, transform.rotation, 0);
		}else
		{
			Network.Instantiate(player, new Vector3(0, 5, 0), transform.rotation, 0);
		}
	}

    void OnPlayerDisconnected(NetworkPlayer player)
    {
        Network.RemoveRPCs(player, 0);
        Network.DestroyPlayerObjects(player);
    }

	void Start() {
	
		respawns = GameObject.FindGameObjectsWithTag("Respawn");
	}
	
	// Update is called once per frame
	void Update () {
	
		players = GameObject.FindGameObjectsWithTag("Player");
		
		if (Network.peerType == NetworkPeerType.Disconnected)
		{
			for (int i = 0; i < players.Length; i++)
			{
				Destroy(players[i]);
			}
		}
		
	}
}
